package site.luojie.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import site.luojie.entity.Resume;
import site.luojie.repository.ResumeRepository;

import java.util.List;
import java.util.Optional;

/**
 * @author jie.luo
 * @since 2020/12/29
 */
@Service
public class ResumeService {

    @Autowired
    private ResumeRepository resumeRepository;

    /**
     * 插入 Resume
     */
    public Resume addResume(Resume resume) {
        return resumeRepository.save(resume);
    }

    /**
     * 根据id查询
     */
    public Resume findById(String id) {
        Optional<Resume> optional = resumeRepository.findById(id);
        return optional.orElse(null);
    }

    /**
     * 根据 name 查询
     */
    public Resume findByName(String name) {
        Resume user = new Resume();
        user.setName(name);
        Example<Resume> example = Example.of(user);
        Optional<Resume> optional = resumeRepository.findOne(example);
        return optional.orElse(null);
    }

    /**
     * 根据 city 分页查询
     */
    public Page<Resume> findByPage(int pageNum,
                                   int pageSize,
                                   String city) {
        Resume user = new Resume();
        user.setCity(city);
        Example<Resume> example = Example.of(user);
        if (pageNum < 1) {
            pageNum = 1;
        } else if (pageSize == 0) {
            pageSize = 20;
        }

        PageRequest pageable = PageRequest.of(pageNum - 1, pageSize);
        return resumeRepository.findAll(example, pageable);
    }

    /**
     * 根据 expectSalary 排序
     */
    public List<Resume> findBySort(String city) {
        Resume user = new Resume();
        user.setCity(city);
        Example<Resume> example = Example.of(user);
        Sort sort = new Sort(Sort.Direction.ASC, "expectSalary");
        return resumeRepository.findAll(example, sort);
    }

    /**
     * 通过 description 模糊查询
     */
    public Page<Resume> findByDescription(int pageNumber,
                                          int pageSize,
                                          String description) {
        if (pageNumber < 1) {
            pageNumber = 1;
        } else if (pageSize == 0) {
            pageSize = 20;
        }
        PageRequest pageable = PageRequest.of(pageNumber - 1, pageSize);
        return resumeRepository.findByDescriptionLike(null == description ? "" : description, pageable);

    }

    /**
     * 通过 id 删除
     */
    public void deleteById(String id) {
        resumeRepository.deleteById(id);
    }
}
